package com.sciencep.pro.admin.system.common.handler;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.sciencep.pro.common.config.Constant;
import com.sciencep.pro.common.domain.ResponseResult;
import com.sciencep.pro.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;

import static com.sciencep.pro.common.config.Constant.ErrorCode.HTTP_MESSAGE_NOT_READABLE_MESSAGE;

@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult<Object> handleException(Exception e) {
        log.error("系统内部异常，异常信息：", e);
        return new ResponseResult<>().failure(Constant.ErrorCode.SYSTEM_ERROR, e.getMessage());
    }

    @ExceptionHandler(value = CustomException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult<Object> handleParamsInvalidException(CustomException e) {
        log.error("自定义异常错误：{}", e.getMessage());
        return new ResponseResult<>().failure(Constant.ErrorCode.SYSTEM_ERROR,e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult<Object> validationErrorHandler(MethodArgumentNotValidException e, HttpServletRequest request){

        StringBuilder sb  = new StringBuilder();
        List<FieldError> fieldErrors =  e.getBindingResult().getFieldErrors();
        sb.append("验证失败:");
        fieldErrors.stream().forEach(t -> sb.append(t.getDefaultMessage()));

        return new ResponseResult<>().failure(Constant.ErrorCode.VALIDATE_ERROR,sb.toString());
    }

    /**
     * 统一处理请求参数校验(实体对象传参)
     *
     * @param e BindException
     * @return oscaResponse
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult<Object> validExceptionHandler(BindException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(StringPool.COMMA);
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return new ResponseResult<>().failure(Constant.ErrorCode.VALIDATE_ERROR,message.toString());

    }

    /**
     * 统一处理请求参数校验(普通传参)
     *
     * @param e ConstraintViolationException
     * @return oscaResponse
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult<Object> handleConstraintViolationException(ConstraintViolationException e) {
        StringBuilder message = new StringBuilder();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            Path path = violation.getPropertyPath();
            String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), StringPool.DOT);
            message.append(pathArr[1]).append(violation.getMessage()).append(StringPool.COMMA);
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return new ResponseResult<>().failure(Constant.ErrorCode.VALIDATE_ERROR, message.toString());
    }

    @ExceptionHandler(value = UnauthorizedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public void handleUnauthorizedException(Exception e) {
        log.error("权限不足，{}", e.getMessage());
    }

    @ExceptionHandler(value = AuthenticationException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResponseResult<Object> handleAuthenticationException(AuthenticationException e) {
        log.error("自定义异常错误：{}", e.getMessage());
        return new ResponseResult<>().failure(Constant.ErrorCode.UNAUTHORIZED_ERROR,e.getMessage());
    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult<Object> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.info(e.getMessage());
        return new ResponseResult<>().failure(Constant.ErrorCode.HTTP_MESSAGE_NOT_READABLE_ERROR, HTTP_MESSAGE_NOT_READABLE_MESSAGE);
    }
}
